<?php
ini_set('display_errors', 'On');
error_reporting(1);

require_once("xmlClass.php");

function getPost($isVarName) {
	if(isset($_POST[$isVarName])) {
		return htmlspecialchars($_POST[$isVarName]);
	} else {
		return null;
	}
}
function getGet($isVarName) {
	if(isset($_GET[$isVarName])) {
		return htmlspecialchars($_GET[$isVarName]);
	} else {
		return null;
	}
}

function nvl($var1, $var2) {
	if(empty($var1)) {
		return $var2;
	} else {
		return $var1;
	}
}

function ThrowException($isException, $ibDie = true) {
	echo "Exception: ".$isException;
	if($ibDie) {
		die();
	}
}

function GetIP() {
	return $_SERVER['REMOTE_ADDR'];
}

function GetDateString() {
	return date('Y-m-d H:i:s');
}

class BaseClass {
	public $SQL;
	private $LogFile;

	function __construct() {
		$this->OpenWSLogFile();
	}

	function __destruct() {
		$this->CloseWSLogFile();
	}

	public function DBConnect() {
		$this->SQL = new mysqli("localhost", "czmikulas", "mikulass", "czmikulas");
		if ($this->SQL->connect_errno) {
		    ThrowException("Failed to connect to MySQL: (" . $this->SQL->connect_errno . ") " . $this->SQL->connect_error);
		}
		$this->SQL->set_charset("utf8");
	}

	public function returnError($isErrorMessage) {
		die("<error>".$isErrorMessage."</error>");
	}

	public function getInput($isInputName = "input") {
		$lsInputInBase64 = getGet($isInputName);
		$lsInput = $this->base64url_decode($lsInputInBase64);
		if (empty($lsInput)) {
		    ThrowException("NO_INPUT_FOUND");
		} 
		$this->WriteWSLog("Request input: ".$lsInput);
		return $lsInput;
	}

	public function SendResponse($isResponse) {
		$this->WriteWSLog("Response: ".$isResponse);
		echo $isResponse;
	}

	public function ParseXMLInput($isInput) {
		try {
		   $lrXMLObject = new SimpleXMLElement($isInput);
		} catch (Exception $e) {
		   ThrowException($e->getMessage());
		}
		return $lrXMLObject;
	}

	private function OpenWSLogFile() {
		try {
			$this->LogFile = fopen('./WSLog.txt', 'a');
		}
		catch (Exception $e) {
			ThrowException($e->getMessage());
		}
	}

	private function WriteWSLog($isText) {
		fwrite($this->LogFile, GetDateString()." (".GetIP().") - ".$isText."\r\n");
	}

	private function CloseWSLogFile() {
		fclose($this->LogFile);
	}

	private function base64url_decode($data) { 
	  return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT)); 
	} 

	private function base64url_encode($data) { 
  		return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
	} 
}


?>